<?php

namespace app\admin\controller\kefu;

use Throwable;
use app\worker\library\kefu\Common;
use app\common\controller\Backend;

/**
 * 消息汇总记录管理
 */
class Message extends Backend
{
    /**
     * Message模型对象
     * @var object
     * @phpstan-var \app\admin\model\kefu\Message
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected array $withJoinTable = ['sender', 'recipient'];

    protected string|array $quickSearchField = ['id'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\kefu\Message();
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        // 如果是 select 则转发到 select 方法，若未重写该方法，其实还是继续执行 index
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->visible(['sender' => ['nickname'], 'recipient' => ['nickname']])
            ->paginate($limit)
            ->each(function ($item) {
                if ($item->sender_id && $item->sender) {
                    $item->sender->nickname = Common::trueValue([
                        $item->sender->nickname,
                        $item->sender->admin?->nickname,
                        $item->sender->sysUser?->nickname,
                        Common::getTouristNickname($item->sender->id),
                    ]);
                }
                if ($item->recipient_id && $item->recipient) {
                    $item->recipient->nickname = Common::trueValue([
                        $item->recipient->nickname,
                        $item->recipient->admin?->nickname,
                        $item->recipient->sysUser?->nickname,
                        Common::getTouristNickname($item->recipient->id),
                    ]);
                }
            });

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
}